<script lang="ts" setup>
import { onBeforeMount, ref, toRaw } from 'vue';
import 'ant-design-vue/es/message/style/index.css';

import 'vditor/dist/index.css';
import { deleteProblem, getProblemList, Problem, ProblemEasy } from '@/api/problem';

import message from 'ant-design-vue/es/message';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();


const currentPage = ref<number>(1);
const nextPageUrl = ref('');
const prevPageUrl = ref('');

const isLoading = ref(false);


const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'id',
  },
  {
    title: '原题链接',
    dataIndex: 'remote_oj',
    key: 'remote_url',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '更新时间',
    key: 'updateTime',
    dataIndex: 'updateTime',
  },
  {
    title: '管理',
    key: 'setting',
    dataIndex: 'id',
  },
];
const list = ref<ProblemEasy[]>([]);
const fetchProblemList = async (page: number, remote?: number , other?: object) => {
  isLoading.value = true;
  try {
    const res: { results: [], next: string, previous: string } = await getProblemList(page, remote , other);
    nextPageUrl.value = res.next;
    prevPageUrl.value = res.previous;
    currentPage.value = page;
    isLoading.value = false;
    list.value = res.results;
  } catch (error) {
    console.error('Error fetching problem list:', error);
    isLoading.value = false;
  }
};

function goToPreviousPage() {
  const newPage = currentPage.value - 1;
  const remote = Number(route.params.remote) || null;
  const newQuery = { ...route.query, page: newPage };
  router.push({ path: route.path, query: newQuery });
  fetchProblemList(newPage , remote, newQuery);
}

function goToNextPage() {
  const newPage = currentPage.value + 1;
  const remote = Number(route.params.remote) || null;
  const newQuery = { ...route.query, page: newPage };
  router.push({ path: route.path, query: newQuery });
  fetchProblemList(newPage ,remote, newQuery);
}


onBeforeMount(async () => {
  const remote = Number(route.params.remote) || null;
  const { query: { page } } = route;
  if (page != null) {
    currentPage.value = Number(page) || 1;
  }

  if (remote != null) {
    await fetchProblemList(currentPage.value, remote);
  } else {
    await fetchProblemList(currentPage.value);
  }
});

const handleProblemShow = async (current: { id: any; }) => {
  await router.push({
    name: 'AdminProblemDetail',
    params: {
      action: 'show',
      problemId: current.id
    }
  });
};
const handleProblemEdit = async (current: { id: any; }) => {
  await router.push({
    name: 'AdminProblemDetail',
    params: {
      action: 'edit',
      problemId: current.id
    }
  });
};
const handleProblemDelete = async (current: any) => {
  await deleteProblem(current.id);
  message.success(`删除题目[${current.id}]成功`);
  await fetchProblemList(currentPage.value);
};

const handleProblemAdd = () => {
  router.push({
    name: 'AdminAddProblemFromRemote',
  });
};

const jumpToProblemPage = (problemId: number) => {
  window.open(`/problem/${problemId}`, '_blank');
};
const handleTitleClick = (e: PointerEvent, item: Problem) => {
  jumpToProblemPage(item.id);
};


</script>

<template>
  <div style="display: flex; flex-direction: column">
    <nav aria-label="breadcrumb">
      <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="/admin/user">管理员设置</a></li>
        <li class="breadcrumb-item active" aria-current="page">题目管理</li>
      </ol>
    </nav>
    <a-button v-show="!isLoading" type="primary" @click="handleProblemAdd">新建题目</a-button>
    <div v-if="isLoading" class="loading-overlay">
      <a-spin size="large"/>
    </div>
    <transition name="list-fade">
      <a-table :columns="columns" :data-source="list" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <a-button type="link" @click="(e) => handleTitleClick(e, toRaw(record))">
              {{ record.remote_oj + record.remote_id + ' . ' + record.title }}
            </a-button>
          </template>
          <template v-if="column.key === 'remote_url'">
            <a :href="record.remote_url" target="_blank">{{ record.remote_oj + record.remote_id }}</a>
          </template>
          <template v-if="column.key === 'setting'">
            <div style="display: flex; justify-content: space-around; flex-wrap: wrap">
              <a-button size="small" @click="handleProblemShow(record)">查看</a-button>
              <a-button type="primary" size="small" @click="handleProblemEdit(record)">修改</a-button>
              <a-button danger size="small" @click="handleProblemDelete(record)">删除</a-button>
            </div>
          </template>
          <template v-if="column.key === 'createTime' || column.key === 'updateTime'">
            {{ new Date(record[column.dataIndex]).toLocaleString() }}
          </template>
        </template>
      </a-table>
    </transition>
    <div class="pagination">
      <a-button v-show="!isLoading" :disabled="!prevPageUrl" @click="goToPreviousPage">上一页</a-button>
      <a-button v-show="!isLoading" :disabled="!nextPageUrl" @click="goToNextPage">下一页</a-button>
    </div>
  </div>
</template>

<style scoped lang="less">
.sample-list {
  display: flex;
  line-height: 36px;
  border-bottom: 1px solid #eee;

  &-name {
    width: 25%;
  }

  &-size {
    width: 15%;
  }

  &-md5 {
    width: 60%;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}


.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
